package cn.itcast.service.impl;
import cn.itcast.dao.UserDao;
import cn.itcast.entity.PageResult;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Stream;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 添加用户,角色
     * @param user
     * @param roles
     */
    @Transactional
    @Override
    public void add(User user, Integer[] roles) {
        //保存检查组基本信息
        userDao.add(user);
        //关联保存检查项信息
        if (roles != null && roles.length!=0) {
            Integer userId = user.getId();
            setUserAndRole(userId, roles);
        }
    }

    /**
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 单条查询
     * @param id
     * @return
     */
    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    /**
     * 通过用户id 查询关联角色
     * @param userId
     * @return
     */
    @Override
    public Integer[] selectedRolesId(Integer userId) {
        return userDao.findRolesAssociationIds(userId);
    }


    @Transactional
    @Override
    public void update(User user, Integer[] roleIds) {

        //删除检查组关联检查项信息
        userDao.deleteRolesAssociation(user.getId());
        //设置检查组关联检查项信息
        setUserAndRole(user.getId(), roleIds);
        //更新检查组基本信息
        userDao.update(user);
    }



    @Transactional
    @Override
    public void deleteById(Integer id) {
        //删除关联信息
        userDao.deleteRolesAssociation(id);
        //删除检查组基本信息
        userDao.deleteById(id);
    }


    private void setUserAndRole(Integer userId, Integer[] roleIds) {
        Stream.of(roleIds).forEach(roleId-> userDao.setRolesAssociation(userId,roleId));
    }

}
